using SPI.AgentServer.Services.Metadata;

namespace SPI.AgentServer.Services.Tools;

public class DescribeTableTool : IQueryTool
{
    private readonly ISchemaRegistry _schemaRegistry;
    private readonly ILogger<DescribeTableTool> _logger;

    public string Name => "describe_table";
    public string Description => "Get table structure information";

    public DescribeTableTool(ISchemaRegistry schemaRegistry, ILogger<DescribeTableTool> logger)
    {
        _schemaRegistry = schemaRegistry;
        _logger = logger;
    }

    public async Task<ToolResult> ExecuteAsync(Dictionary<string, object> parameters, CancellationToken cancellationToken = default)
    {
        if (!ValidateParameters(parameters, out var errors))
        {
            return new ToolResult
            {
                Success = false,
                Errors = errors
            };
        }

        var tableName = parameters["tableName"].ToString()!;
        // 兼容 database 和 databaseName 两种参数名
        var database = parameters.ContainsKey("database") ? parameters["database"]?.ToString() 
                     : parameters.ContainsKey("databaseName") ? parameters["databaseName"]?.ToString() 
                     : null;

        try
        {
            var schema = await _schemaRegistry.GetTableSchemaAsync(tableName, database, cancellationToken);
            
            if (schema == null)
            {
                return new ToolResult
                {
                    Success = false,
                    Errors = new List<string> { $"Table '{tableName}' not found" }
                };
            }

            // Get sample queries
            var sampleQueries = await _schemaRegistry.GetSampleSqlAsync(tableName, database, cancellationToken);

            var result = new
            {
                tableName = schema.TableName,
                schemaName = schema.SchemaName,
                database = schema.DatabaseName,
                columns = schema.Columns.Select(c => new
                {
                    name = c.ColumnName,
                    type = c.DataType,
                    maxLength = c.MaxLength,
                    nullable = c.IsNullable,
                    primaryKey = c.IsPrimaryKey,
                    identity = c.IsIdentity,
                    defaultValue = c.DefaultValue
                }),
                primaryKeys = schema.PrimaryKeys,
                sampleQueries = sampleQueries
            };

            return new ToolResult
            {
                Success = true,
                Data = result
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error describing table: {TableName}", tableName);
            return new ToolResult
            {
                Success = false,
                Errors = new List<string> { $"Error: {ex.Message}" }
            };
        }
    }

    public bool ValidateParameters(Dictionary<string, object> parameters, out List<string> errors)
    {
        errors = new List<string>();

        if (!parameters.ContainsKey("tableName") || string.IsNullOrWhiteSpace(parameters["tableName"]?.ToString()))
        {
            errors.Add("Parameter 'tableName' is required and cannot be empty");
        }

        return errors.Count == 0;
    }
}
